package com.swfee.qinben;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.SimpleAdapter;
import android.widget.ViewFlipper;

import com.swfee.qinben.adpt.CalendarGridView;
import com.swfee.qinben.adpt.CalendarGridViewAdapter;
import com.swfee.qinben.base.AppBaseActivity;
import com.swfee.qinben.dto.rsp.ScheduleDayRspDto;
import com.swfee.qinben.httpactions.ScheduleAction;
import com.swfee.qinben.session.SystemConfig;
import com.swfee.qinben.util.CurenActivitUtils;

/**
 * 
 * @author ddr
 * 
 */
public class T3Activity extends AppBaseActivity implements OnTouchListener {
	/**
	 * 日历布局ID
	 */
	private static final int CAL_LAYOUT_ID = 55;
	// 判断手势用
	private static final int SWIPE_MIN_DISTANCE = 120;

	private static final int SWIPE_MAX_OFF_PATH = 250;

	private static final int SWIPE_THRESHOLD_VELOCITY = 200;

	private SimpleDateFormat dateFmt = new SimpleDateFormat("yyyy年M月");
	private int todayMonth = 0;
	private int todayYear = 0;

	// /**
	// * 用于传递选中的日期
	// */
	// private static final String MESSAGE = "msg";

	// 动画
	private Animation slideLeftIn;
	private Animation slideLeftOut;
	private Animation slideRightIn;
	private Animation slideRightOut;
	private ViewFlipper viewFlipper;
	GestureDetector mGesture = null;

	/**
	 * 今天按钮
	 */
	private View mTodayBtn;

	/**
	 * 上一个月按钮
	 */
	private View mPreMonthImg;

	/**
	 * 下一个月按钮
	 */
	private View mNextMonthImg;

	/**
	 * 用于显示今天的日期
	 */
	// private TextView mDayMessage;

	/**
	 * 用于装截日历的View
	 */
	public LinearLayout mCalendarMainLayout;

	// 基本变量
	private Context mContext = this;
	/**
	 * 上一个月View
	 */
	private GridView firstGridView;

	/**
	 * 当前月View
	 */
	private GridView currentGridView;

	/**
	 * 下一个月View
	 */
	private GridView lastGridView;

	/**
	 * 当前显示的日历
	 */
	private Calendar calStartDate = Calendar.getInstance();

	/**
	 * 选择的日历
	 */
	private Calendar calSelected = Calendar.getInstance();

	/**
	 * 今日
	 */
	private Calendar calToday = Calendar.getInstance();

	/**
	 * 当前界面展示的数据源
	 */
	private CalendarGridViewAdapter currentGridAdapter;

	/**
	 * 预装载上一个月展示的数据源
	 */
	private CalendarGridViewAdapter firstGridAdapter;

	/**
	 * 预装截下一个月展示的数据源
	 */
	private CalendarGridViewAdapter lastGridAdapter;

	//
	/**
	 * 当前视图月
	 */
	private int mMonthViewCurrentMonth = 0;

	/**
	 * 当前视图年
	 */
	private int mMonthViewCurrentYear = 0;

	/**
	 * 起始周
	 */
	private int iFirstDayOfWeek = Calendar.MONDAY;

	List<ScheduleDayRspDto> scheduleDayRspDtos;

	@Override
	public boolean onTouch(View v, MotionEvent event) {
		return mGesture.onTouchEvent(event);
	}

	Handler handler = new Handler() {

		public void handleMessage(android.os.Message msg) {
			initView();
			updateStartDateForMonth();
			generateContetView(mCalendarMainLayout);
			;
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Date date = new Date();
		todayMonth = date.getMonth();
		todayYear = date.getYear() + 1900;
		setContentView(R.layout.loading_view);
//		showProgressDialog();
//		//设置loading 图片
//		GifView laoding = (GifView)findViewById(R.id.loading_gif);
//		laoding.setGifImage(R.drawable.loading);
		//
		new Thread(new Runnable() {

			@Override
			public void run() {
				ScheduleAction action = new ScheduleAction();
				scheduleDayRspDtos = action.getAllScheduleDay();
				handler.sendEmptyMessage(1);
			}
		}).start();
		//
		//

	}

	/**
	 * 用于初始化控件
	 */
	private void initView() {

		setContentView(R.layout.calendar_main);
		slideLeftIn = AnimationUtils.loadAnimation(this, R.anim.push_left_in);
		slideLeftOut = AnimationUtils.loadAnimation(this, R.anim.push_left_out);
		slideRightIn = AnimationUtils.loadAnimation(this, R.anim.push_right_in);
		slideRightOut = AnimationUtils.loadAnimation(this,
				R.anim.push_right_out);

		slideLeftIn.setAnimationListener(animationListener);
		slideLeftOut.setAnimationListener(animationListener);
		slideRightIn.setAnimationListener(animationListener);
		slideRightOut.setAnimationListener(animationListener);

		mGesture = new GestureDetector(this, new GestureListener());

		mTodayBtn = findViewById(R.id.to_today);
		mPreMonthImg = findViewById(R.id.prev);
		mNextMonthImg = findViewById(R.id.next);

		View prevEx = findViewById(R.id.prev_ex);
		View nextEx = findViewById(R.id.next_ex);

		prevEx.setOnClickListener(onPreMonthClickListener);
		nextEx.setOnClickListener(onNextMonthClickListener);

		mTodayBtn.setOnClickListener(onTodayClickListener);
		mPreMonthImg.setOnClickListener(onPreMonthClickListener);
		mNextMonthImg.setOnClickListener(onNextMonthClickListener);
		mCalendarMainLayout = (LinearLayout) findViewById(R.id.calendar_main);

		// 日期抬头 周-到周日
		String[] arrayTitls = "周一,周二,周三,周四,周五,周六,周日".split(",");
		if (SystemConfig.weekFirstDayIsSunday()) {
			arrayTitls = "周日,周一,周二,周三,周四,周五,周六".split(",");
		}
		List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
		for (int i = 0; i < 7; i++) {
			Map<String, Object> item = new HashMap<String, Object>();
			item.put("weekTitle", arrayTitls[i]);
			items.add(item);
		}
		SimpleAdapter weekTitleGridAdapter = new SimpleAdapter(this, items,
				R.layout.days_title, new String[] { "weekTitle" },
				new int[] { R.id.weekTitle });

		GridView weekTitleGridView = (GridView) findViewById(R.id.weekTitleGridView);
		weekTitleGridView.setAdapter(weekTitleGridAdapter);

	}

	/**
	 * 用于加载到当前的日期的事件
	 */
	private View.OnClickListener onTodayClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View view) {

			if (mMonthViewCurrentMonth == todayMonth
					&& todayYear == mMonthViewCurrentYear) {
				return;
			}

			viewFlipper.setInAnimation(null);
			viewFlipper.setDisplayedChild(1);
			setCurViewItem();

		}
	};

	/**
	 * 用于加载上一个月日期的事件
	 */
	private View.OnClickListener onPreMonthClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View view) {
			viewFlipper.setInAnimation(slideRightIn);
			viewFlipper.setOutAnimation(slideRightOut);
			viewFlipper.showPrevious();
			setPrevViewItem();
		}
	};

	/**
	 * 用于加载下一个月日期的事件
	 */
	private View.OnClickListener onNextMonthClickListener = new View.OnClickListener() {
		@Override
		public void onClick(View view) {
			viewFlipper.setInAnimation(slideLeftIn);
			viewFlipper.setOutAnimation(slideLeftOut);
			viewFlipper.showNext();
			setNextViewItem();
		}
	};

	/**
	 * 主要用于生成发前展示的日历View
	 * 
	 * @param layout
	 *            将要用于去加载的布局
	 */
	private void generateContetView(LinearLayout layout) {
		// 创建一个垂直的线性布局（整体内容）
		viewFlipper = new ViewFlipper(this);
		viewFlipper.setId(CAL_LAYOUT_ID);
		calStartDate = getCalendarStartDate();
		createGirdView();
		RelativeLayout.LayoutParams params_cal = new RelativeLayout.LayoutParams(
				LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
		layout.addView(viewFlipper, params_cal);

		RelativeLayout br = new RelativeLayout(this);
		RelativeLayout.LayoutParams params_br = new RelativeLayout.LayoutParams(
				LayoutParams.FILL_PARENT, 1);
		params_br.addRule(RelativeLayout.BELOW, CAL_LAYOUT_ID);
		layout.addView(br, params_br);

	}

	/**
	 * 用于创建当前将要用于展示的View
	 */
	private void createGirdView() {

		Calendar firstCalendar = Calendar.getInstance(); // 临时
		Calendar currentCalendar = Calendar.getInstance(); // 临时
		Calendar lastCalendar = Calendar.getInstance(); // 临时
		firstCalendar.setTime(calStartDate.getTime());
		currentCalendar.setTime(calStartDate.getTime());
		lastCalendar.setTime(calStartDate.getTime());

		firstGridView = new CalendarGridView(mContext);
		firstCalendar.add(Calendar.MONTH, -1);
		firstGridAdapter = new CalendarGridViewAdapter(this, firstCalendar,
				scheduleDayRspDtos);
		firstGridView.setAdapter(firstGridAdapter);// 设置菜单Adapter
		firstGridView.setId(CAL_LAYOUT_ID);

		currentGridView = new CalendarGridView(mContext);
		currentGridAdapter = new CalendarGridViewAdapter(this, currentCalendar,
				scheduleDayRspDtos);
		currentGridView.setAdapter(currentGridAdapter);// 设置菜单Adapter
		currentGridView.setId(CAL_LAYOUT_ID);

		lastGridView = new CalendarGridView(mContext);
		lastCalendar.add(Calendar.MONTH, 1);
		lastGridAdapter = new CalendarGridViewAdapter(this, lastCalendar,
				scheduleDayRspDtos);
		lastGridView.setAdapter(lastGridAdapter);// 设置菜单Adapter
		lastGridView.setId(CAL_LAYOUT_ID);

		currentGridView.setOnTouchListener(this);
		firstGridView.setOnTouchListener(this);
		lastGridView.setOnTouchListener(this);

		if (viewFlipper.getChildCount() != 0) {
			viewFlipper.removeAllViews();
		}

		viewFlipper.addView(currentGridView);
		viewFlipper.addView(lastGridView);
		viewFlipper.addView(firstGridView);
		// String s = calStartDate.get(Calendar.YEAR)
		// + "-"
		// + NumberHelper.LeftPad_Tow_Zero(calStartDate
		// .get(Calendar.MONTH) + 1);
		// // mDayMessage.setText(s);
		CurenActivitUtils.setHeaderTitle(dateFmt.format(calStartDate.getTime())
				+ "日程", 2);
	}

	/**
	 * 上一个月
	 */
	private void setPrevViewItem() {
		mMonthViewCurrentMonth--;// 当前选择月--
		// 如果当前月为负数的话显示上一年
		if (mMonthViewCurrentMonth == -1) {
			mMonthViewCurrentMonth = 11;
			mMonthViewCurrentYear--;
		}
		calStartDate.set(Calendar.DAY_OF_MONTH, 1); // 设置日为当月1日
		calStartDate.set(Calendar.MONTH, mMonthViewCurrentMonth); // 设置月
		calStartDate.set(Calendar.YEAR, mMonthViewCurrentYear); // 设置年

	}

	/**
	 * 上一个月
	 */
	private void setCurViewItem() {
		Date date = new Date();

		mMonthViewCurrentMonth = date.getMonth();
		mMonthViewCurrentYear = date.getYear() + 1900;
		calStartDate = Calendar.getInstance();
		calSelected = Calendar.getInstance();
		calToday = Calendar.getInstance();

		calStartDate.set(Calendar.DAY_OF_MONTH, 1); // 设置日为当月1日
		calStartDate.set(Calendar.MONTH, mMonthViewCurrentMonth); // 设置月
		calStartDate.set(Calendar.YEAR, mMonthViewCurrentYear); // 设置年

	}

	/**
	 * 下一个月
	 */
	private void setNextViewItem() {
		mMonthViewCurrentMonth++;
		if (mMonthViewCurrentMonth == 12) {
			mMonthViewCurrentMonth = 0;
			mMonthViewCurrentYear++;
		}
		calStartDate.set(Calendar.DAY_OF_MONTH, 1);
		calStartDate.set(Calendar.MONTH, mMonthViewCurrentMonth);
		calStartDate.set(Calendar.YEAR, mMonthViewCurrentYear);

	}

	/**
	 * 根据改变的日期更新日历 填充日历控件用
	 */
	private void updateStartDateForMonth() {
		calStartDate.set(Calendar.DATE, 1); // 设置成当月第一天
		mMonthViewCurrentMonth = calStartDate.get(Calendar.MONTH);// 得到当前日历显示的月
		mMonthViewCurrentYear = calStartDate.get(Calendar.YEAR);// 得到当前日历显示的年
		// mDayMessage.setText(s);
		// String s = dateFmt.format(calStartDate);
		// 星期一是2 星期天是1 填充剩余天数
		CurenActivitUtils.setHeaderTitle(dateFmt.format(calStartDate.getTime())
				+ "日程", 2);
		int iDay = 0;
		if (SystemConfig.weekFirstDayIsSunday()) {
			iDay = calStartDate.get(Calendar.DAY_OF_WEEK) - Calendar.SUNDAY;
			if (iDay < 0)
				iDay = 6;
		} else {
			iDay = calStartDate.get(Calendar.DAY_OF_WEEK) - Calendar.MONDAY;
			if (iDay < 0)
				iDay = 6;
		}
		calStartDate.add(Calendar.DAY_OF_WEEK, -iDay);

	}

	/**
	 * 用于获取当前显示月份的时间
	 * 
	 * @return 当前显示月份的时间
	 */
	private Calendar getCalendarStartDate() {
		calToday.setTimeInMillis(System.currentTimeMillis());
		calToday.setFirstDayOfWeek(iFirstDayOfWeek);

		if (calSelected.getTimeInMillis() == 0) {
			calStartDate.setTimeInMillis(System.currentTimeMillis());
			calStartDate.setFirstDayOfWeek(iFirstDayOfWeek);
		} else {
			calStartDate.setTimeInMillis(calSelected.getTimeInMillis());
			calStartDate.setFirstDayOfWeek(iFirstDayOfWeek);
		}

		return calStartDate;
	}

	AnimationListener animationListener = new AnimationListener() {
		@Override
		public void onAnimationStart(Animation animation) {
		}

		@Override
		public void onAnimationRepeat(Animation animation) {
		}

		@Override
		public void onAnimationEnd(Animation animation) {
			// 当动画完成后调用
			createGirdView();
		}
	};

	class GestureListener extends SimpleOnGestureListener {
		@Override
		public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
				float velocityY) {
			try {
				if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
					return false;
				// right to left swipe
				if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					viewFlipper.setInAnimation(slideLeftIn);
					viewFlipper.setOutAnimation(slideLeftOut);
					viewFlipper.showNext();
					setNextViewItem();
					return true;

				} else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
						&& Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
					viewFlipper.setInAnimation(slideRightIn);
					viewFlipper.setOutAnimation(slideRightOut);
					viewFlipper.showPrevious();
					setPrevViewItem();
					return true;

				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			return false;
		}

		@Override
		public boolean onSingleTapUp(MotionEvent e) {
			// 得到当前选中的是第几个单元格
			int pos = currentGridView.pointToPosition((int) e.getX(),
					(int) e.getY());
			LinearLayout txtDay = (LinearLayout) currentGridView
					.findViewById(pos + 5000);
			if (txtDay != null) {
				if (txtDay.getTag() != null) {
					Date date = (Date) txtDay.getTag();
					// if (CalendarUtil.compare(date,
					// Calendar.getInstance().getTime())>=0) {
					calSelected.setTime(date);
					currentGridAdapter.setSelectedDate(calSelected);
					currentGridAdapter.notifyDataSetChanged();
					firstGridAdapter.setSelectedDate(calSelected);
					firstGridAdapter.notifyDataSetChanged();

					lastGridAdapter.setSelectedDate(calSelected);
					lastGridAdapter.notifyDataSetChanged();
					// String week = CalendarUtil.getWeek(calSelected);
					// String message = CalendarUtil.getDay(calSelected) + " 农历"
					// + new CalendarUtil(calSelected).getDay() + " "
					// + week;
					// Toast.makeText(getApplicationContext(),
					// "您选择的日期为:" + message, Toast.LENGTH_SHORT).show();
					// } else {
					// Toast.makeText(getApplicationContext(), "选择的日期不能小于今天的日期",
					// Toast.LENGTH_SHORT).show();
					// }
					Intent intent = new Intent();
					intent.setClass(T3Activity.this, MyScheduleListActivity.class);
					T3Activity.this.startActivity(intent);
				}
			}

			// Log.i("TEST", "onSingleTapUp -  pos=" + pos);

			return false;
		}
	}
}